#!/usr/bin/env python
import sys;
import os; 
import commands;
import re;
from optparse import OptionParser;
from xml.dom.minidom import parse, parseString;
from time import gmtime, strftime;

#Set the root directory and grep host
tutorial_root=commands.getoutput('pwd')
host_tag=os.uname()[1];

parser = OptionParser()
parser.add_option("-a", "--account", help="account name",type="string", dest="acc", default="MAT001QMC")
parser.add_option("-e", "--exe", help="pull path of qmcapp",type="string", dest="exe",default="../qmcapp")
parser.add_option("-i", "--id",  help="unique name for database, e.g., jaguar", type="string", default=host_tag,dest="id")
parser.add_option("-n", "--np", help="number of mpi nodess", type="string", dest="np", default="1")
parser.add_option("-t", "--threads", help="number of threads", type="string", dest="omp", default="1")
parser.add_option('-p','--pbs',help="pbs script template",type='string',dest='pbs',default='j.pbs.template')

(options, args) = parser.parse_args(sys.argv[1:])

template_file=tutorial_root+'/'+options.pbs
mydir=options.id+"."+strftime("%m-%d-%y_%H%M", gmtime());

#parse qmcapp.xml to get the test lists
dom = parse('qmcapp.xml')  
items=dom.getElementsByTagName('item') 

#store pbs template file
r=open(template_file,"r");
pbs=r.read()
r.close()

if not os.path.isdir(mydir):
  os.makedirs(mydir)

print 'Changing directory to '+mydir
os.chdir(mydir)


#loop over item in qmcapp
for a in items:

  dirname=a.getAttribute('name')

  #copy input file in a directory    
  inp=a.getAttribute('input')
  tinp=inp 
  if(inp=='qmc.xml'): tinp=dirname+'.qmc.xml' 
  commands.getoutput('cp '+tutorial_root+'/'+dirname+'/'+inp+' '+tinp)
  
  #replace QMC keyword to generate new scripts
  qmcout=dirname+'.out'
  t=pbs.replace('QMCAPP',options.exe).replace('QMCINP',tinp).replace('QMCOUT',qmcout).replace('QMCACC',options.acc).replace('QMCOMP',options.omp)
  
  #make add MAKELINK and REMOVELINK to *.pbs
  flist=a.getAttribute('files')
  if(flist == ""):
    t=t.replace('MAKELINK',' ').replace('REMOVELINK',' ')
  else:
    link_txt=""
    rm_txt='rm -f '
    for f in flist.split(' '):
      link_txt +='ln -s ' +tutorial_root+'/'+dirname+'/'+f+' .\n'
      rm_txt += ' '+f
    t=t.replace('MAKELINK',link_txt).replace('REMOVELINK',rm_txt)
    
  jfile=open(dirname+'.pbs',"w")
  jfile.write(t)
  jfile.close()

  print 'To submit a job: qsub '+dirname+'.pbs'

